#include "app_modbus.h"

static modbus_t *modbus;
gate_status_t app_modbus_init(void)
{
    if (modbus)
    {
        return GATE_OK;
    }

    // 1. 创建modbus上下文
    modbus = modbus_new_rtu("/dev/ttyS1", 115200, 'N', 8, 1);
    if (modbus == NULL)
    {
        log_error("modbus_new_rtu error");
        return GATE_ERROR;
    }

    // 2. 启用调试模式(生产环境关闭)
    modbus_set_debug(modbus, true);

    // 3. 连接(起始打开串口)
    if (modbus_connect(modbus) == -1)
    {
        modbus_free(modbus);
        return GATE_ERROR;
    }

    return GATE_OK;
}

void app_modbus_deinit(void)
{
    modbus_close(modbus);
    modbus_free(modbus);
}

/**
 * @brief 写单个保持寄存器
 *
 * @param slaveAddr 从机地址
 * @param value 写入的寄存器的值  (寄存器地址定死: 0)
 */
gate_status_t app_modbus_writeSingleHoldRegister(uint8_t slaveAddr, uint16_t value)
{
    // 设置从机地址
    modbus_set_slave(modbus, slaveAddr);

    // 向指定的寄存器写入数据
    int res = modbus_write_register(modbus, 0, value);
    if (res == -1)
    {
        log_info("modbus_write_register error");
        return GATE_ERROR;
    }
    return GATE_OK;
}

/**
 * @brief 读取单个输入寄存器
 *
 * @param slaveAddr  从机地址
 * @param value 存储读取到寄存器的值
 */
gate_status_t app_modbus_readSigleInputRegister(uint8_t slaveAddr, uint16_t *value)
{
    // 设置从机地址
    modbus_set_slave(modbus, slaveAddr);

    int res = modbus_read_input_registers(modbus, 0, 1, value);
    if (res == -1)
    {
        log_info("modbus_read_input_registers error");
        return GATE_ERROR;
    }
    return GATE_OK;
}
